<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SqlClient</title>
    <link href="/static/js/resources/ext-theme-neptune/ext-theme-neptune-all.css" rel="stylesheet"/>
    <script src="/static/js/ext-all.js" type="text/javascript"></script>
    <script src="/static/js/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
    <script src="/static/js/MyVTypes.js" type="text/javascript"></script>
    <script src="/static/js/utils.js" type="text/javascript"></script>

    <link href="/static/codemirror/lib/codemirror.css" rel="stylesheet"/>
    <link href="/static/codemirror/addon/hint/show-hint.css" rel="stylesheet"/>
    <link href="/static/codemirror/theme/idea.css" rel="stylesheet"/>

    <script src="/static/codemirror/lib/codemirror.js" type="text/javascript"></script>
    <script src="/static/codemirror/mode/sql/sql.js" type="text/javascript"></script>
    <script src="/static/codemirror/addon/hint/show-hint.js" type="text/javascript"></script>
    <script src="/static/codemirror/addon/hint/sql-hint.js" type="text/javascript"></script>
    <script src="/static/codemirror/addon/selection/active-line.js" type="text/javascript"></script>

    <script type="text/javascript">

       var localStore = new myLocalStore();
       var my_localStore = new Ext.state.LocalStorageProvider();
       var scenes_name = '';
       var seq_name = '';

       function init_page(scenes_name, seq_name) {
           scenes_name = scenes_name;
           seq_name = seq_name;
           //console.log('新的 scenes_name: ' + scenes_name);
           //console.log('新的 node_seq_name: ' + seq_name);
           /*
           var node_obj = my_localStore.get('node_seq_name');
           if (node_obj != null) {
               var scenes_obj = my_localStore.decodeValue(node_obj);
               scenes_name = scenes_obj.scenes_name;
               seq_name = scenes_obj.seq_name;
               console.log('scenes_name: ' + scenes_name);
               console.log('node_seq_name: ' + seq_name);
           } else {
               return;
           }
           */
       }

       Ext.define('cn.plus.tree.Panel', {
                   extend: 'Ext.tree.Panel',
                   url: '',
                   listeners: {
                       "itemexpand": function (node, event) {
                           //console.log(node);
                           //console.log(event);
                           if (node.isLeaf()) {
                               event.stopEvent();
                           }
                       },
                       'itemclick': function (node, record, item, index, e, eOpts) {
                         e.stopEvent();
                     }
                   },
                   rootVisible: false,
                   initComponent: function () {
                       var me = this;

                       var store = Ext.create('Ext.data.TreeStore', {
                           proxy: {
                               type: 'ajax',
                               //url: '/extjs_case/get_tree_store/',
                               url: me.url,
                               reader: {
                                   type: 'json',
                                   root: 'root'
                               }
                           },
                           root: {
                               expanded: true,
                               text: '根节点'
                           }
                       });

                       var base_config = {
                           store: store
                       };

                       Ext.apply(this, base_config);
                       this.callParent();
                   }
               });

       Ext.application({
           name: 'MyEdit',
           launch: function() {

               var node_obj = my_localStore.get('node_seq_name');
               if (node_obj != null) {
                   var scenes_obj = my_localStore.decodeValue(node_obj);
                   scenes_name = scenes_obj.scenes_name;
                   seq_name = scenes_obj.seq_name;
                   console.log('scenes_name: ' + scenes_name);
                   console.log('node_seq_name: ' + seq_name);
               }

               var editor;

               var store = null;

               // 每页显示条数下拉选择框
               var pagesize_combo = null;
               var number = 50;
               // 分页工具栏
               var bbar = null;
               var grid = null;

               /**
                * 生成一个 textarea
                * */
               Ext.DomHelper.append(document.body, {tag: 'textarea', id: 'code_area'});

               var code_area_panel = Ext.create('Ext.panel.Panel', {
                   anchor: '100%',
                   resizable: {
                       handles: 's'
                   },
                   listeners: {
                       resize: function(obj, width, height, oldWidth, oldHeight, eOpts){
                           if (typeof(editor) != 'undefined' && editor)
                           {
                               editor.setSize('auto', height + 'px');
                           }
                       }
                   },
                   contentEl: 'code_area'
               });

               var source = {"users": ["id", "name"], "dbs": ["id", "name"]};
               //var source = eval('(' + document.getElementById('table_info').innerText + ')');

               var edit_form = Ext.create('Ext.form.Panel', {
                   /**
                    * 定义 eidt form
                    * */
                   id: 'edit_form',
                   itemId: 'edite_win',
                   layout: "form",
                   defaults: {
                       anchor: '100%'
                   },
                   buttonAlign: "center",
                   labelAlign: "right",
                   items: [code_area_panel, {
                       id: 'p_grid',
                       itemId: 'p_grid',
                       bodyStyle :'overflow-x:hidden;overflow-y:scroll',
                       //height: 480,
                       //bodyStyle:'overflow-x:hidden;overflow-y:auto;',
                       border: true,
                       hidden: true
                   }, {
                       itemId: 'p_error',
                       hidden: true
                   }],
                   listeners: {
                       "afterrender": function (m) {
                           //var pg = Ext.getCmp('p_grid');
                           //console.log(pg);
                           //Ext.getCmp('p_error').hide();
                       }
                   }
               });

               // 右导航

               var tbar = Ext.create('Ext.toolbar.Toolbar', {
                   enableOverflow: true,
                   items: [{
                       text: '运行',
                       handler: function () {
                           var vs = Ext.String.trim(editor.getSelection());
                           if (vs == '') {
                               vs = Ext.String.trim(editor.getValue());
                           }

                           if (vs != '') {
                               Ext.Msg.wait('正在运行，请稍候...', '信息提示');
                               Ext.Ajax.request({
                                   url: '/edite/run_sql/',
                                   method: 'GET',
                                   params: {
                                       code: vs
                                   },
                                   success: function (response) {
                                       Ext.Msg.hide();
                                       var sql_node = localStore.findSql_node(scenes_name, seq_name);
                                       if (sql_node != null)
                                       {
                                           sql_node['is_run'] = 1;
                                           localStore.updateNode(scenes_name, sql_node);
                                       }

                                       /**
                                        * 生成 Grid
                                        * */
                                       var result = Ext.decode(response.responseText);
                                       if (exist_key(result, 'error')) {
                                           var p_grid = edit_form.getComponent('p_grid');
                                           p_grid.hide();
                                           var p_error = edit_form.getComponent('p_error');
                                           p_error.removeAll();
                                           //console.log(p_error.getHeight());
                                           var panel_panel = Ext.getCmp('panel_panel');
                                           p_error.setHeight(panel_panel.getHeight() - 127 - 20);
                                           p_error.add(Ext.create('Ext.Component', {
                                               html: '&nbsp;&nbsp;<a target="_blank" href="/doc/compile_error/?q='+ result.msg +'">'+ result.msg +'</a>'
                                           }));
                                           p_error.show();
                                       }
                                       else {
                                           var sorters = result.sorters;
                                           var sql_line = '';
                                           if (exist_key(result, 'sql_line'))
                                           {
                                               sql_line = result.sql_line;
                                           }

                                           var sql_count_line = '';
                                           if (exist_key(result, 'sql_count_line'))
                                           {
                                               sql_count_line = result.sql_count_line;
                                           }

                                           var args = '';
                                           if (exist_key(result, 'args'))
                                           {
                                               args = result.args;
                                           }

                                           var java_code = '';
                                           if (exist_key(result, 'java_code'))
                                           {
                                               java_code = result.java_code;
                                           }

                                           var limit_begin = 0;
                                           var limit_end = 0;
                                           var page_limit = 50;
                                           if (exist_key(result, 'limit'))
                                           {
                                               limit_begin = result.limit.begin;
                                               if (result.limit.end != 0) {
                                                   limit_end = result.limit.end;
                                                   page_limit = result.limit.end;
                                                   number = result.limit.end;
                                               }
                                           }

                                           var fields = '[';
                                           for (var i = 0; i < result.fields.length; i++)
                                           {
                                               if (i == result.fields.length - 1)
                                               {
                                                   fields += '"'+ result.fields[i] +'"';
                                               }
                                               else {
                                                   fields += '"'+ result.fields[i] +'",';
                                               }
                                           }
                                           fields += ']';

                                           store = new Ext.data.JsonStore({
                                               proxy: {
                                                   type: 'ajax',
                                                   url: '/edite/run_sql_store/',
                                                   //method: 'POST',
                                                   actionMethods: {create: 'POST', read: 'POST', update: 'POST', destroy: 'POST'},
                                                   reader: {
                                                       type: 'json',
                                                       root: "root",
                                                       totalProperty: "totalProperty"
                                                   }
                                               },
                                               remoteSort: true,
                                               //fields: ['chk', 'id', 'templateName', 'atomicity', 'backups', 'cacheMode', 'write_synchronization_mode', 'data_region', 'nodeFilter', 'description'],
                                               fields: result.fields,
                                               sorters: sorters
                                               /*
                                           sorters: [{
                                               property: 'id',
                                               direction: 'DESC'
                                           }]
                                            */
                                           });

                                           pagesize_combo = new Ext.form.ComboBox({
                                               triggerAction: 'all',
                                               mode: 'local',
                                               store: new Ext.data.ArrayStore({
                                                   fields: ['value', 'text'],
                                                   data: [[page_limit, page_limit + '条/页'], [100, '100条/页'], [250, '250条/页'], [500, '500条/页']]
                                               }),
                                               valueField: 'value',
                                               displayField: 'text',
                                               value: page_limit,
                                               editable: false,
                                               width: 85
                                           });

                                           number = parseInt(pagesize_combo.getValue());
                                           // 改变每页显示条数reload数据
                                           pagesize_combo.on("select", function (comboBox) {
                                               bbar.pageSize = parseInt(comboBox.getValue());
                                               number = parseInt(comboBox.getValue());
                                               store.reload({
                                                   params: {
                                                       limit_begin: limit_begin,
                                                       limit_end: limit_end,
                                                       sql_line: sql_line,
                                                       sql_count_line: sql_count_line,
                                                       args: args,
                                                       java_code: java_code,
                                                       fields: fields,
                                                       start: 0,
                                                       limit: bbar.pageSize
                                                   }
                                               });
                                           });

                                           bbar = new Ext.PagingToolbar({
                                               pageSize: number,
                                               store: store,
                                               displayInfo: true,
                                               displayMsg: '当前记录 {0} -- {1} 条 共 {2} 条记录',
                                               prevText: "上一页",
                                               nextText: "下一页",
                                               refreshText: "刷新",
                                               lastText: "最后页",
                                               firstText: "第一页",
                                               beforePageText: "当前页",
                                               afterPageText: "共{0}页",
                                               emptyMsg: "没有符合条件的记录",
                                               items: ['-', '&nbsp;&nbsp;', pagesize_combo]
                                           });

                                           grid = new Ext.grid.GridPanel({
                                               autoHeight: true,
                                               stripeRows: true,
                                               store: store,
                                               columns: result.columns,
                                               autoScroll: true,
                                               border: true,
                                               viewConfig: {
                                                   columnsText: "显示/隐藏列",
                                                   sortAscText: "正序排列",
                                                   sortDescText: "倒序排列",
                                                   forceFit: true
                                               },
                                               loadMask: {
                                                   msg: '正在加载数据，请稍等．．．'
                                               },
                                               bbar: bbar,
                                               listeners: {
                                                   'contextmenu': function (e) {
                                                       e.stopEvent();
                                                   }
                                               }
                                           });

                                           store.on('beforeload', function (store) {
                                               Ext.apply(store.proxy.extraParams, {
                                                   limit_begin: limit_begin,
                                                   limit_end: limit_end,
                                                   sql_line: sql_line,
                                                   sql_count_line: sql_count_line,
                                                   args: args,
                                                   java_code: java_code,
                                                   fields: fields
                                               });

                                           });

                                           store.load({
                                               params: {
                                                   limit_begin: limit_begin,
                                                   limit_end: limit_end,
                                                   sql_line: sql_line,
                                                   sql_count_line: sql_count_line,
                                                   args: args,
                                                   java_code: java_code,
                                                   fields: fields,
                                                   start: 0,
                                                   limit: bbar.pageSize
                                               }
                                           });

                                           var p_error = edit_form.getComponent('p_error');
                                           p_error.hide();
                                           var p_grid = edit_form.getComponent('p_grid');
                                           p_grid.removeAll();
                                           //console.log(p_grid.getHeight());
                                           var panel_panel = Ext.getCmp('panel_panel');
                                           p_grid.setHeight(panel_panel.getHeight() - 280);
                                           p_grid.add(grid);
                                           p_grid.show();
                                       }
                                   },
                                   failure: function (response) {
                                       var sql_node = localStore.findSql_node(scenes_name, seq_name);
                                       if (sql_node != null)
                                       {
                                           sql_node['is_run'] = 0;
                                           localStore.updateNode(scenes_name, sql_node);
                                       }
                                       var result = Ext.decode(response.responseText);
                                       Ext.Msg.show({
                                           title: '错误提示',
                                           msg: result.msg,
                                           buttons: Ext.Msg.OK,
                                           minWidth: 100
                                       });
                                   }
                               });
                           }

                       }
                   }, '-', {
                       text: '设置节点',
                       handler: function () {
                           var vs = Ext.String.trim(editor.getSelection());
                           if (vs == '') {
                               vs = editor.getValue();
                           }

                           if (vs == '') {
                               Ext.MessageBox.alert('提示', '设置节点的内容为空！');
                               return;
                           }

                           var sql_node = localStore.findSql_node(scenes_name, seq_name);
                           if (sql_node != null && sql_node['is_run'] == 0)
                           {
                               Ext.MessageBox.alert('提示', '代码必须执行确保正确后才能保存！');
                               return;
                           }

                           if (seq_name == '')
                           {
                               Ext.MessageBox.alert('提示', '节点名字必须为空！');
                               return;
                           }

                           if (seq_name != '' && vs != '' && sql_node != null && sql_node['is_run'] == 1) {
                               window.parent.add_to_node(scenes_name, seq_name, vs);
                           }
                       }
                   }]
               });

               Ext.create('Ext.Viewport', {
                   layout: 'border',
                   title: 'MyPlus 的主界面',
                   defaults: {
                       //collapsible: true,
                       split: true
                   },
                   listeners: {
                       mouseUp: function () {
                           console.log('OK');
                       }
                   },
                   items: [{
                       xtype: 'panel',
                       region: 'north',
                       height: 30,
                       border: false,
                       tbar: tbar
                   }, {
                       region: 'west',
                       itemId: 'west_panel',
                       xtype: 'panel',
                       title: '提示',
                       width: 200,
                       split: true,
                       collapsible: true,
                       floatable: false,
                       items: [Ext.create('cn.plus.sugest_tree')]
                   }, {
                       region: 'center',
                       xtype: 'panel',
                       id: 'panel_panel',
                       //itemId: 'panel_panel',
                       items: [edit_form],
                       listeners: {
                           afterrender: function (obj) {
                               editor = CodeMirror.fromTextArea(document.getElementById('code_area'), {//根据DOM元素的id构造出一个编辑器
                                   lineNumbers: true,
                                   styleActiveLine: true,
                                   theme: "idea",//设置主题
                                   mode: 'text/x-mysql',
                                   //mode : 'text/x-plsql',
                                   hintOptions: {tables: source}
                               });
                               editor.setSize('auto', '227px');
                               editor.on("keyup", function (cm, event) {
                                   if (!cm.state.completionActive//所有的字母和'$','{','.'在键按下之后都将触发自动完成
                                       && ((event.keyCode >= 65 && event.keyCode <= 90)
                                           || event.keyCode == 52 || event.keyCode == 219
                                           || event.keyCode == 190)) {
                                       CodeMirror.commands.autocomplete(cm, null, {
                                           completeSingle: false
                                       });
                                   }

                                   var sql_node = localStore.findSql_node(scenes_name, seq_name);
                                   if (sql_node != null) {
                                       sql_node.sql = editor.getValue();
                                       localStore.updateNode(scenes_name, sql_node);
                                   }
                               });

                               var sql_node = localStore.findSql_node(scenes_name, seq_name);
                               if (sql_node != null && sql_node.sql != '') {
                                   editor.setValue(sql_node.sql);
                               }
                           }
                       },
                       bodyStyle :'overflow-x:hidden;overflow-y:scroll',
                       hidden: false
                   }]
               });
           }
       });
    </script>
</head>
<body>
<div id="table_info" style="display:none;">
       {{ obj }}
    </div>
</body>
</html>